package com.bjc.base.controller;

import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bjc.base.bean.request.UserReqVO;
import com.bjc.base.bean.response.UserVO;
import com.bjc.base.service.IUserService;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;


@RestController
@RequestMapping("/wechat/user")
@Slf4j
public class WxUserController {

	@Autowired
	private WxMpService wxMpService;
	@Autowired
	private IUserService userService;

	/**
	 * <pre>
	 * 当用户同意授权后，会回调所设置的url并把authorization code传过来，
	 * 然后用这个code获得access token，其中也包含用户的openid等信息
	 *
	 * @param menu
	 * @return 如果是个性化菜单，则返回menuid，否则返回null
	 */
	@GetMapping("/get")
	public WxMpUser getUser(@PathParam("code") String code) throws WxErrorException {
		log.info("根据code:" + code + ",获取用户id");
		WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
		WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
//		wxMpOAuth2AccessToken = wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
		//boolean valid = wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
		UserReqVO record = new UserReqVO();
		String openid = wxMpUser.getOpenId();
		log.info("已获取openid:" + openid);
		record.setOpenid(openid);
		UserVO user = userService.get(record);
		String userid = user.getId().toString();
		log.info("已获取userid:" + userid);
		wxMpUser.setRemark(userid);
		return wxMpUser;
	}

}
